package com.itbaizhan.service.impl;


import com.itbaizhan.entity.UserAccount;
import com.itbaizhan.mapper1.UserAccountMapper1;

import com.itbaizhan.mapper2.UserAccountMapper2;
import com.itbaizhan.service.IUserAccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itbaizhan
 * @since 07-06
 */
/*由于具体的XA跨库分布式事务是由Atomikos框架内部实现的，
因此在业务逻辑层处理跨库转账的逻辑时，就像操作本地数据库一样简单。在方法上加注解@Transactional*/
@Service
public class UserAccountServiceImpl  implements IUserAccountService {


    @Autowired
    private UserAccountMapper1 userAccountMapper1;
    @Autowired
    private UserAccountMapper2 userAccountMapper2;
    /**
     * 跨库转账
     * @param sourceAccountNo 转出账户
     * @param targetSourceNo 转入账户
     * @param transferAmount 金额
     */
    @Transactional  //解决分库的强一致性问题
    @Override
    public void transfer(String sourceAccountNo, String targetSourceNo, BigDecimal transferAmount) {

        //1,查询转出用户
        UserAccount sourceAccount = userAccountMapper1.selectById(sourceAccountNo);
        //2查询转入用户
        UserAccount targetAccount = userAccountMapper2.selectById(targetSourceNo);

        //3判断两个账户是否为空
        if(sourceAccount != null && targetAccount != null){

            //4判断转出账户是否全余额不足
            if(sourceAccount.getAccountBalance().compareTo(transferAmount) < 0 ){
                throw  new RuntimeException("余额不足");
            }
           //更新转出账户  subtract() 减法
            sourceAccount.setAccountBalance(sourceAccount.getAccountBalance().subtract(transferAmount));
            //更新数据库
            userAccountMapper1.updateById(sourceAccount);

            //System.out.println(10/0);
            //更新转入账户 add() 加
            targetAccount.setAccountBalance(targetAccount.getAccountBalance().add(transferAmount));
            userAccountMapper2.updateById(targetAccount);
        }
    }
}
